<template>
  <el-form
    :model="formData"
    ref="formRef"
    vloading="formLoading"
    label-width="auto"
    :rules="formRules"
  >
    <el-row>
      <el-form-item label="名称" prop="name" class="mr-3">
        <el-input v-model="formData.name" :clearable="true" style="width: 400px" />
      </el-form-item>

      <el-form-item label="类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择类型">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MARKET_TEMPLATE_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-button
        style="margin-left: auto"
        type="primary"
        :disabled="formLoading"
        @click="submitForm"
      >
        保 存
      </el-button>
      <el-button @click="closeCurrentPage()">取 消</el-button>
    </el-row>
    <el-row>
      <el-form-item label="主题" prop="subject" style="flex-grow: 1; margin-right: 20px">
        <el-input v-model="formData.subject" :clearable="true" style="flex-grow: 1" />
      </el-form-item>

      <el-popover :width="150" :visible="subjectMacroVisible">
        <el-button
          v-for="(item, index) in subjectMacro"
          class="ml-3"
          style="border: none; min-width: 120px"
          :key="index"
          @click="handleSubjectMacroClick(index)"
        >
          {{ item }}
        </el-button>

        <template #reference>
          <el-button @click="subjectMacroVisible = !subjectMacroVisible"> 主题宏 </el-button>
        </template>
      </el-popover>
    </el-row>
  </el-form>
  <div style="display: flex">
    <UploadFile
      v-model="fileList"
      :show-file-list="false"
      :is-show-tip="false"
      class="mr-3"
      :fileSize="32"
    >
      <el-button><Icon icon="mdi:paperclip" />附件</el-button>
    </UploadFile>
    <el-popover :width="150" :visible="contentMacroVisible">
      <el-button
        v-for="(item, index) in contentMacro"
        class="ml-3"
        style="border: none; min-width: 120px"
        :key="index"
        @click="handleContentMacroClick(index)"
      >
        {{ item }}
      </el-button>

      <template #reference>
        <el-button @click="contentMacroVisible = !contentMacroVisible"> 正文宏 </el-button>
      </template>
    </el-popover>
  </div>
  <FileList v-model="fileList">
    <template #menu="{ item }">
      <context-menu-item label="删除" @click="handleDeleteResource(item)" />
      <context-menu-item label="重命名" @click="handleRenameResource(item)" />
      <context-menu-item label="复制附件名" @click="handleCopyResourceName(item)" />
    </template>
  </FileList>
  <div style="flex: 1">
    <Editor ref="editorRef" height="calc(100vh - 300px)" v-model="formData.content.content" />
  </div>

  <RenameFile ref="renameFileRef" @success="saveResourceName" />
</template>
<script setup name="MarketTemplateEdit" lang="ts">
import UploadFile from '@/components/UploadFile/src/UploadFile.vue'
import * as MarketTemplateApi from '@/api/market/marketTemplate'
import type { UploadUserFile } from 'element-plus'
import FileList from '@/components/UploadFile/src/FileList.vue'
import RenameFile from '@/components/UploadFile/src/RenameFile.vue'
import { MailboxMailResourceTypeEnum } from '@/utils/constants'
import { subjectMacro, contentMacro } from '@/views/market/marketMacro/macro'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { useTagsViewStore } from '@/store/modules/tagsView'
const { currentRoute, push } = useRouter()
const tagsViewStore = useTagsViewStore()
const { t } = useI18n() // 国际化
const renameFileRef = ref()
const editorRef = ref()
const subjectMacroVisible = ref(false)
const contentMacroVisible = ref(false)

const message = useMessage() // 消息弹窗
const formRules = reactive({
  name: [{ required: true, message: '请输入名称', trigger: 'change' }],
  subject: [{ required: true, message: '请输入主题', trigger: 'change' }]
})

const formRef = ref()
const formLoading = ref(false)
const formData = ref({
  id: undefined,
  name: undefined as any,
  type: 1,
  subject: '' as string,
  resources: [] as any[],
  content: { content: '' }
})

const formType = ref('create')
const fileList = ref<UploadUserFile[]>([])
/** 打开弹窗 */
onActivated(async () => {
  resetData()
  if (history.state.type == 'update') {
    formData.value = await MarketTemplateApi.singleGet(history.state.id)
    formType.value = 'update'
  }
  if (history.state.type == 'copy') {
    formData.value = await MarketTemplateApi.singleGet(history.state.id)
    formData.value.id = undefined
    formData.value.name = ''
  }
  if (formData.value.resources.length > 0) {
    formData.value.resources.forEach((resource) => {
      if (resource.resourceType == MailboxMailResourceTypeEnum.ATTACHMENT)
        fileList.value.push({
          name: resource.fileName,
          url: resource.urlName,
          size: resource.size
        })
    })
  }
})
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const resetData = () => {
  subjectMacroVisible.value = false
  contentMacroVisible.value = false
  fileList.value = []
  formData.value = {
    id: undefined,
    name: undefined as any,
    type: 1,
    subject: '' as string,
    resources: [] as any[],
    content: { content: '' }
  }
}

const handleDeleteResource = (item) => {
  fileList.value = fileList.value.filter((resourceItem) => {
    if (resourceItem == item) return false
    else return true
  })
}

const handleRenameResource = (item) => {
  const index = fileList.value.indexOf(item)
  renameFileRef.value.open(index, item.name)
}

const handleCopyResourceName = async (item) => {
  await navigator.clipboard.writeText(item.name)
}

const saveResourceName = (index, name) => {
  fileList.value[index].name = name
}

const handleSubjectMacroClick = (index) => {
  formData.value.subject = formData.value.subject + '%' + subjectMacro[index] + '%'
  subjectMacroVisible.value = false
}

const handleContentMacroClick = (index) => {
  editorRef.value
    .getEditorRef()
    .getEditor()
    .insertContent('%' + contentMacro[index] + '%')
  contentMacroVisible.value = false
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  formData.value.resources = []
  fileList.value.forEach((file) => {
    formData.value.resources.push({
      fileName: file.name,
      urlName: file.url,
      resourceType: MailboxMailResourceTypeEnum.ATTACHMENT,
      size: file.size
    })
  })
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.content.content == '') {
    message.error('模板正文不能为空')
    return
  }
  if (formType.value == 'create') {
    await MarketTemplateApi.create(formData.value)
    message.success(t('common.createSuccess'))
  } else {
    await MarketTemplateApi.update(formData.value)
    message.success(t('common.updateSuccess'))
  }
  closeCurrentPage()
  emit('success')
}

const closeCurrentPage = () => {
  if (unref(currentRoute)?.meta?.affix) return
  tagsViewStore.delView(unref(currentRoute))
  const visitedViews = tagsViewStore.getVisitedViews
  const latestView = visitedViews.slice(-1)[0]
  if (latestView) {
    push(latestView)
  } else {
    push('/')
  }
}
</script>
